<?php
// check if the user is logged-in
include 'authentication.php';
isAuthorized();

// Contain variable "rootDir"
include_once('../utils/directories.php');
include_once($_SERVER["DOCUMENT_ROOT"]."/web-doc/protected/database/MySqlDAO.php");
include_once ($_SERVER["DOCUMENT_ROOT"]."/web-doc/protected/messages/it/messages.php");
                
if (!empty($_GET['idc'])) {
    $idc = $_GET['idc'];
    if (!empty($_POST['isToInsert'])) {
        if (!empty($_POST['name'])) {

            $name = $_POST['name'];
            
            $mySqlDAO = new MySqlDAO();

            /* Check if the category already exist in the same path */
            $idcres = $mySqlDAO->checkCategoryName($idc, $name);
            if (empty($idcres)){
                $target_path = $mySqlDAO->getCategoryPath($idc);

                $path = getRootDir() . $target_path . $name . DIRECTORY_SEPARATOR;
                
                $old = umask(0);
                mkdir($path, 0777) or die("ERROR: Cannot make dir " . $path);
                umask($old);

                $dbPath = $target_path . $name . DIRECTORY_SEPARATOR;
                $res = $mySqlDAO->createCategory($name, $dbPath, $idc);

                if (empty($res)) {
                    rmdir($path);
                    echo $messages['createcategory.error1'];
                }                    
                else
                    header("Location: showcategory.php?idc=$idc");
            }
            else {
                 echo $messages['createcategory.name_already_used'];
            }
        } else {
            echo $messages['createcategory.missing_data'];
        }
    }
} else {
    die("ERRORE: Missing parent directory. <a href=javascript:history.back(-1)>Back</a>");
}

if(!isset($name))
    $name ="";
?>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="../styles/main.css">
        <link rel="stylesheet" type="text/css" href="../styles/admin.css">
        <title>WebDoc - Create category</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data" action="createcategory.php?idc=<?php echo $idc ?>">
            <table width="450" border="0" cellpadding="1" cellspacing="1" class="box">
                <tr>
                    <td valign="top" colspan="2">
                        Nome: <input type="text" name="name" size="50" maxlength="150" value="<?php echo $name ?>">
                        <input type="hidden" name="isToInsert" value="true">
                    </td>
                </tr>
                <tr>
                    <td width="80" colspan="2">
                        <br><br>
                        <input type="submit" value="Crea" />
                        <!--<input name="upload" type="submit" class="box" id="upload" value=" Upload ">-->
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

